// app/service/schedule.js
const Service = require("egg").Service;
const schedule = require("node-schedule");

class ScheduleService extends Service {
  constructor(ctx) {
    super(ctx);
    this.SysJobLogService = ctx.service.monitor.sysJobLog;
  }

  // 创建定时任务
  async create(name, cron, invoke_target, task) {
    if (this.ctx.app.jobs[name]) {
      this.ctx.app.jobs[name].cancel();
    }
    this.ctx.app.jobs[name] = schedule.scheduleJob(cron, async () => {
      let errCode = "";
      let res = "";
      try {
        res = await eval(`this.ctx.service.${invoke_target}`);
      } catch (error) {
        errCode = JSON.stringify(error);
      }
      await this.SysJobLogService.create({
        job_name: task.job_name,
        job_group: task.job_group,
        invoke_target: task.invoke_target,
        job_message: JSON.stringify(res),
        status: errCode ? "1" : "0",
        exception_info: errCode,
        create_time: new Date(),
      });
    });
    console.log(1);
  }

  // 修改定时任务
  async update(name, newCron) {
    if (this.ctx.app.jobs[name]) {
      this.ctx.app.jobs[name].reschedule(newCron);
    }
  }

  // 暂停定时任务
  async pause(name) {
    if (this.ctx.app.jobs[name]) {
      this.ctx.app.jobs[name].cancel();
      delete this.ctx.app.jobs[name];
    }
  }

  // 恢复定时任务
  async resume(name, cron) {
    if (this.ctx.app.jobs[name]) {
      this.ctx.app.jobs[name].reschedule(cron);
    } else {
      this.ctx.logger.warn(`Job ${name} does not exist.`);
    }
  }

  // 执行一次定时任务
  async runOnce(name) {
    if (this.ctx.app.jobs[name]) {
      this.ctx.app.jobs[name].invoke();
    }
  }

  // 获取所有的定时任务
  async getAllJobs() {
    return this.ctx.app.jobs;
  }
}

module.exports = ScheduleService;
